import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { useUserStoreHook } from '@/store/modules/user';
import { useAppStoreHook } from '@/store/modules/app';


let loadingInstance: any;
// 记录当前页⾯请求总次数
let loadingRequestCount = 0;
function showLoading() {
  if (loadingRequestCount === 0) {
    
    loadingInstance = ElLoading.service({
      fullscreen: true,
      lock: true,
      text: 'loading',
      spinner: '',
      background: 'rgba(0, 0, 0, 0.1)',
    
    });
    //console.log('showloading',loadingRequestCount)
  }

  loadingRequestCount++;
}

function closeLoading() {
  //console.log('closeloading',loadingRequestCount);
  if (loadingRequestCount <= 0) return;
  loadingRequestCount--;
  if (loadingRequestCount === 0) {
    loadingInstance.close();
  }
}
const whiteturl = ['/connect/token', '/api/abp/application-configuration', '/api/account/logout',
  '/api/identity/my-profile']
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if(whiteturl.indexOf(config.url)==-1)
    {
    showLoading();
    }
    const userStore = useUserStoreHook();
    config.headers['accept-language'] = useAppStoreHook().language;
    // config.headers.common['X-Requested-With'] = 'XMLHttpRequest'
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    //  console.log('request',response);
    closeLoading();
    const { code, msg } = response.data;
    if (response.status === 200 || response.status === 204) {

      //console.log(response)
      return response.data;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    ElMessage.error(msg || '系统出错');
    return Promise.reject(new Error(msg || 'Error'));
  },
  (error: any) => {
   // console.log('request error', error)
    closeLoading();
    if (error.response) {
      if (error.response.data) {
        //console.log('error', error)
        const { code, message } = error.response.data.error;

        console.log('error', { code, message })
        // token 过期,重新登录
        if (error.response.status === 401) {
          if (error.response.data.error_description === 'Invalid username or password!') {

          } else {

           // console.log(error.response.status)
            debugger
            ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              removeLocalStore();
              window.location.href = '/';
            });
          }

        } else if (error.response.status === 400) {
          if (error.response.data.error_description!=null) {
            ElMessageBox.confirm(error.response.data.error_description, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              removeLocalStore();
              window.location.href = '/';
            });
          } else {
   
            ElMessage.error(error.response.data.error.details);
          }

        } else {
          debugger
          ElMessage.error(message || '系统出错');
        }
      }
    } else {
      ElMessage.error(`${error.code}`);
    }
    return Promise.reject(error.message);
  }
);


const removeLocalStore=()=>{
  localStorage.removeItem('accessToken');
  localStorage.removeItem('abpConfig');
}

// 导出 axios 实例
export default service;
